/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tolls;

import avenue.MyWindowEvent;
import avenue.Session;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.DBManager;
import model.ProgramRate;
import model.Vehicle;

/**
 *
 * @author Aggelos
 */
public class CollectTollForm extends javax.swing.JFrame {

    /**
     * Creates new form CollectTollForm
     */
    public CollectTollForm() {
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Διόδια");
        setResizable(false);

        jButton1.setText("ΔΙΕΛΕΥΣΗ");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Αρ. Κάρτας: ");

        jLabel1.setText("Αρ. Κυκλοφορίας: ");

        jButton2.setText("ΠΛΗΡΩΜΗ");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel3.setText("Υπόλοιπο Κάρτας: ");

        jTextField3.setEditable(false);
        jTextField3.setBackground(new java.awt.Color(255, 255, 0));
        jTextField3.setFocusable(false);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/search.gif"))); // NOI18N
        jButton4.setToolTipText("Αναζήτηση ");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(37, 37, 37)
                                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 17, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(37, 37, 37))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
         // Έλεγχος των δεδομένων εισόδου
        if (jTextField1.getText().equals("")) {
            JOptionPane.showMessageDialog(rootPane,"Ο αριθμός κυκλοφορίας είναι κενός.", "Error!", 
             JOptionPane.ERROR_MESSAGE); 
            return;
        } else if (jTextField2.getText().equals("")) { 
             JOptionPane.showMessageDialog(rootPane,"Ο αριθμός της κάρτας είναι κενός.", "Error!", 
             JOptionPane.ERROR_MESSAGE); 
            return;
        }
        
        PaymentForm pf=new PaymentForm(v,false);
        pf.setVisible(true);
        thisFrame=this;
        thisFrame.setEnabled(false);
        
        pf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){
                    jTextField3.setText(String.valueOf(v.getCardId().getBalance()));
                    thisFrame.setEnabled(true);
                }
                else{
                   thisFrame.setEnabled(true);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });                       
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        try{
             Date d1=new Date();
             d1.setDate(1);
             query3=em.createQuery("select c from Collection c where c.passTimestamp>:time1 and c.cardId=:card").setParameter("time1",d1).setParameter("card", v.getCardId());
             List<Collection> list2=query3.getResultList();
             
             if (!(list2.size()>= v.getCardId().getProgramId().getFreeCount() && (list2.size()< v.getCardId().getProgramId().getFreeCount() + v.getCardId().getProgramId().getFreePass()))){
                 query2 = em.createQuery("select pr from ProgramRate pr where pr.programId=:program and pr.categoryId=:category and pr.stationId=:station").setParameter("program",v.getCardId().getProgramId()).setParameter("category",v.getCategoryId()).setParameter("station",Session.loginUser.getStationId());
                 pr =  (ProgramRate)query2.getSingleResult();

                 
                 if (v.getCardId().getBalance() - pr.getRate().doubleValue() < 0){
                 JOptionPane.showMessageDialog(rootPane,"Δεν υπάρχει επαρκές υπόλοιπο", "Error!",
                    JOptionPane.ERROR_MESSAGE);
                
                }else{
                 
                 v.getCardId().setBalance(v.getCardId().getBalance()- pr.getRate().doubleValue());
                 
                 model.Collection col = new model.Collection();
                 em.persist(col);
                 col.setCardId(v.getCardId());
                 col.setPassTimestamp(new Date());
                 col.setTollCollected(pr.getRate());
                 col.setStationId(Session.loginUser.getStationId());
                 }
             }else
             {
                model.Collection col = new model.Collection();
                em.persist(col);
                col.setCardId(v.getCardId());
                col.setPassTimestamp(new Date());
                col.setTollCollected(new BigDecimal(0));
                col.setStationId(Session.loginUser.getStationId());
             
             }
             
             em.getTransaction().commit();
             em.getTransaction().begin();
             jTextField3.setText(String.valueOf(v.getCardId().getBalance()));
  
        }
        catch(Exception ex){
            JOptionPane.showMessageDialog(rootPane,"Δεν έχei εισαχθεί στοιχεία!", "Error!",
                JOptionPane.ERROR_MESSAGE);
        } 
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here: Search Button

        if(!jTextField1.getText().equals("") && (!jTextField2.getText().equals(""))){
            try{
                query1 = em.createQuery("select v from Vehicle v where v.cardId.barcode=:barcode "
                    + "and v.regNumber=:regNumber").setParameter("barcode",Integer.parseInt
                    (jTextField2.getText())).setParameter("regNumber",jTextField1.getText());
                v =  (Vehicle)query1.getSingleResult();
                jTextField3.setText(String.valueOf(v.getCardId().getBalance()));
                
                if (v.getCardId().getBalance() <= 5){
                 JOptionPane.showMessageDialog(rootPane,"Το υπόλοιπό σας είναι λιγότερο από 5 ευρώ", "Error!",
                    JOptionPane.ERROR_MESSAGE);
                
                }
                
            }
            catch(Exception ex){
                JOptionPane.showMessageDialog(rootPane,"Δεν βρέθηκε όχημα με τα στοιχεία που δόθηκαν!", "Error!",
                    JOptionPane.ERROR_MESSAGE);
                jTextField1.setText("");
                jTextField2.setText("");
                
            }
        }
        else{
            JOptionPane.showMessageDialog(rootPane,"Δεν έχουν εισαχθεί επαρκή στοιχεία προς αναζήτηση!", "Error!",
                JOptionPane.ERROR_MESSAGE);
            if ( jTextField1.getText().equals("")){
                jTextField1.grabFocus();}else
            {
                jTextField2.grabFocus();
            }
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CollectTollForm().setVisible(true);
            }
        });
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration//GEN-END:variables
    JFrame thisFrame;
    EntityManager em;
    Vehicle v;
    Query query1;
    Query query2;
    Query query3;
    ProgramRate pr;
}
